<template>
  <div>
    <el-table :data="books" style="width: 100%">
      <el-table-column label="书名" prop="title" />
      <el-table-column label="作者" prop="author" />
      <el-table-column label="年份" prop="publishedYear" />
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="Type to search" />
        </template>
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import axios from 'axios'
import { computed, ref, onMounted } from 'vue'

// 声明一个响应式数组books，用于存储从接口获取的图书数据
const books = ref([])

// 使用onMounted生命周期钩子，当组件挂载到DOM后执行回调函数
onMounted(() => {
  axios.get('http://localhost:8081/books/findAll')
    .then(response => {
      books.value = response.data;
    })
    .catch(error => {
      console.error("There was an error fetching the books:", error);
    });
});

// 搜索关键词
const search = ref('')

// 过滤后的表格数据
const filterTableData = computed(() => {
  // 如果没有搜索关键词，返回全部数据
  if (!search.value) {
    return tableData
  }

  // 转换为小写字母进行不区分大小写的搜索
  const keyword = search.value.toLowerCase()
  return tableData.filter(item => {
    return item.name.toLowerCase().includes(keyword)
  })
})

// 编辑操作
const handleEdit = (index, row) => {
  console.log('编辑', index, row)
}

// 删除操作
const handleDelete = (index, row) => {
  console.log('删除', index, row)
}
</script>
